/**
    颜值评分模块
*/
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
.box {
  min-width: 1140px;
  width: 1140px;
  margin: 0 auto;
  overflow: hidden;
  padding: 70px 0 82px;
  .title {
    text-align: center;
    color: #6c7588;
    padding-bottom: 40px;

    h2 {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 32px;
      position: relative;
    }
    h2:after {
      content: " ";
      position: absolute;
      width: 57px;
      height: 2px;
      background: #6d7588;
      left: 0;
      right: 0;
      margin: auto;
      bottom: -10px;
    }
    .content {
      font-size: 14px;
      line-height: 1.71;
      font-weight: 400;
      color: #434343;
    }
  }
  .function_left {
    width: 518px;
    height: 694px;
    border-radius: 4px;
    background-color: #f6f7fb;
    float: left;
    padding: 20px;
    .image-container {
      width: 480px;
      height: 480px;
      margin: 0 auto 20px;
      border: 1px solid #ddd;
      .face-ImageContainer {
        width: 100%;
        height: 100%;
        position: relative;
        overflow: hidden;
        text-align: center;
        .img {
          width: 100%;
          height: 100%;
          position: relative;
          img {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            max-width: 100%;
            max-height: 100%;
            vertical-align: middle;
          }
        }
      }
    }
    .tips {
      font-size: 26px;
      text-align: center;
      line-height: 478px;
    }
    // img {
    //   width: 478px;
    //   height: 478px;
    // }
    .upload_function {
      display: block;
      content: "";
      clear: both;
      padding-top: 60px;
      .upload_left {
        float: left;

        .host_upload {
          width: 150px;
          height: 36px;
        }
      }
      .upload_right {
        float: right;
        .img_url {
          width: 235px;
          //   height: 37px;
        }
      }
    }
  }
  .function_right {
    width: 600px;
    float: right;
    vertical-align: top;
    height: 694px;
    overflow: hidden;
    border: 1px solid #ddd;
    .tab_head {
      width: 100%;
      .tab_right {
        display: inline-block;
        //   float: left;
        width: 100%;
        background-color: #f6f7fb;
        //   cursor: pointer;
        text-align: center;
        padding: 22px;
        font-size: 16px;
        color: #666;
        text-align: center;
      }
    }
    // .tab_left {
    //   display: inline-block;
    //   float: left;
    //   width: 50%;
    //   background-color: #f6f7fb;
    //   cursor: pointer;
    //   text-align: center;
    //   padding: 22px;
    //   font-size: 16px;
    // }

    .addColor {
      color: #00b2e0;
      background-color: #fff;
    }
    .data_json {
      font-size: 26px;
      text-align: center;
      line-height: 694px;
    }
    .successData_json {
      text-align: left;
      line-height: 45px;
      padding-left: 14px;
    }
  }
}
</style>
<template>
  <div class="box">
    <div class="title">
      <h2>
        <span>功能演示</span>
      </h2>
      <div class="content">从图片中预测人脸的颜值</div>
    </div>
    <div class="function_left">
      <div class="image-container">
        <div class="face-ImageContainer">
          <div class="img">
            <div v-if="!successTryLeft" class="tips">请选择图片进行检测!</div>
            <img :src="successTryImg" v-if="successTryLeft" />
          </div>
        </div>
      </div>

      <div class="upload_function">
        <div class="upload_left">
          <Upload
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccess"
            :before-upload="handBefore"
            :name="'image'"
            action="/web/v1/face/beautyrank"
          >
            <Button icon="ios-cloud-upload" class="host_upload">本地上传</Button>
          </Upload>
        </div>

        <Form ref="formData" :model="form_data" :rules="ruleInline" class="upload_right">
          <Form-item class="img_url" prop="image">
            <Input v-model="form_data.image" placeholder="图片URL" name="img_url">
              <Button
                slot="append"
                type="primary"
                name="create__submit"
                @click="UploadImg_url('formData')"
              >检测</Button>
            </Input>
          </Form-item>
        </Form>
      </div>
    </div>
    <div class="function_right">
      <div class="tab_head">
        <!-- <div
					:class="{addColor:isResult}"
					class="tab_left"
					@click="changeTabResult"
				>
					<span>分析结果</span>
        </div>-->
        <div :class="{addColor:!isResult}" class="tab_right">
          <span>Response JSON</span>
        </div>
      </div>
      <!-- <div v-show="isResult">{{result}}</div> -->
      <pre v-show="!isResult" class="data_json" :class="{successData_json:successTry}">{{data_json}}</pre>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import qs from "qs";

export default {
  data() {
    const checkImg_url = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("图片的URL不能为空"));
      }
      if (
        !/^https?:\/\/.*?(?:gif|png|jpg|jpeg|webp|svg|psd|bmp|tif)$/i.test(
          value
        )
      ) {
        return callback(new Error("请输入正确的URL!"));
      }
      callback();
    };
    return {
      isResult: false,
      data_json: "还未进行检测",
      successTry: false,
      successTryLeft: false,
      result: "还未进行检测",
      successTryImg: null,
      form_data: {
        image: null
      },
      ruleInline: {
        image: [
          {
            validator: checkImg_url,
            required: true,
            trigger: "blur,change"
          }
        ]
      }
    };
  },
  mounted() {},

  methods: {
    // 切换至分析结果
    // changeTabResult() {
    // 	this.isResult = true;
    // },
    // 切换至响应的json
    // changeTabJSON() {
    // 	this.isResult = false;
    // },

    // 提交img_url请求数据
    detect(param) {
      this.$Spin.show();
      this.axios
        .post(
          `${window.location.origin}/web/v1/face/beautyrank`,
          qs.stringify(param)
        )
        .then(({ data }) => {
          if (data.code === 200) {
            this.successTryImg = this.form_data.image;
            this.successTryLeft = true;

            if (data.data.result == "no face detected") {
              this.data_json = "没有检测到人脸";
              this.$Message.error("没有检测到人脸!");
              this.successTry = false;
            } else {
              this.data_json = JSON.stringify(data.data.result[0], null, 2);
              this.successTry = true;
              this.$Message.success("已完成图片检测!");
            }
          } else {
            this.$Spin.hide();
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error(err.message);
        })
        .then(() => {
          this.$Spin.hide();
        });
    },

    /*
        提交图片url的方法
        */
    UploadImg_url(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.detect(this.form_data);
        } else {
          this.$Message.error("你输入的图片url有误");
        }
      });
    },

    /**
     * 格式错误回调
     */
    handleFormatError(file) {
      this.$Spin.hide();
      this.$Notice.warning({
        desc: "图片格式错误!"
      });
    },

    /**
     * 图片尺寸错误回调
     */
    handleMaxSize(file) {
      this.$Spin.hide();
      this.$Message.error("图片不能大于2M!");
    },

    /**
     * 图片上传成功回调
     */
    handleSuccess(res, file) {
      this.$Spin.hide();

      this.successTryLeft = true;

      if (res.data.result == "no face detected") {
        this.data_json = "没有检测到人脸";
        this.$Message.error("没有检测到人脸!");
        this.successTry = false;
      } else {
        this.data_json = JSON.stringify(res.data.result, null, 2);
        this.successTry = true;
        this.$Message.success("已完成图片检测!");
      }
    },

    handBefore(file) {
      this.$Spin.show();

      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const _base64 = reader.result;
        this.successTryImg = _base64; //将_base64赋值给图片的src，实现图片预览
      };
    },

    /**
     * 本地上传失败回调
     */
    handleError() {
      this.$Spin.hide();
      this.successTryLeft = true;

      this.successTry = false;

      this.$Message.error("上传图片失败!");
    }
  }
};
</script>
